$(function () {
    var modal = "<div id='myModal' class='modal hide fade'><div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button><h3>新闻内容预览</h3></div><div id='modal-html' class='modal-body'></div></div>";

    function initToolbarBootstrapBindings() {
        var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
                'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
                'Times New Roman', 'Verdana'],
            fontTarget = $('[title=Font]').siblings('.dropdown-menu');
        $.each(fonts, function (idx, fontName) {
            fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
        });
        $('a[title]').tooltip({container: 'body'});
        $('.dropdown-menu input').click(function () {
            return false;
        })
            .change(function () {
                $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
            })
            .keydown('esc', function () {
                this.value = '';
                $(this).change();
            });

        $('[data-role=magic-overlay]').each(function () {
            var overlay = $(this), target = $(overlay.data('target'));
            overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
        });
        if ("onwebkitspeechchange"  in document.createElement("input")) {
            var editorOffset = $('#editor').offset();
            $('#voiceBtn').css('position', 'absolute').offset({top: editorOffset.top, left: editorOffset.left + $('#editor').innerWidth() - 35});
        } else {
            $('#voiceBtn').hide();
        }
    };
    function showErrorAlert(reason, detail) {
        var msg = '';
        if (reason === 'unsupported-file-type') {
            msg = "无法解析的文件格式" + detail;
        }
        else {
            console.log("上传文件失败", reason, detail);
        }

        $("#alerts").showError("上传文件失败", msg);
    };
    initToolbarBootstrapBindings();
    $('#editor').wysiwyg({fileUploadError: showErrorAlert});
    window.prettyPrint && prettyPrint();

    $(document).find("body").append(modal);

    $('#myModal').on('show', function () {
        $('#modal-html').empty();
        $('#modal-html').html($('#editor').html());
    });
    function showhtml() {
        $('#myModal').modal('toggle');
    }
    $('#editor').keydown(function (e) {
        if (e.keyCode == 40) {
            $('#editor').append("<div><br></div>");
        }
    });
    var linkInput = $("#hyperLink")
    linkInput.focusout(function(){
        $('#editor').append("<a href='" + $(this).val() + "' target='_blank'>" + $(this).val() + "</a>");
        $(this).val('')
    })
    $.extend({
        showModal: showhtml
    });
});